# 导入 Tkinter 模块
import tkinter as tk

# 定义股票历史数据
stock = [
    {"price": 10, "up": True},
    {"price": 15, "up": True},
    {"price": 11, "up": False},
    {"price": 19, "up": True},
    {"price": 12, "up": False},
    {"price": 12.5, "up": True},
    {"price": 13, "up": False},
    {"price": 11.5, "up": True}
]

# 计算概率（先验概率）
def probability(data):
    # 样本数量
    count = len(data)
    # 上涨股票的数量
    up_count = 0
    # 上涨股票的总价
    up_sum = 0
    # 下跌股票的数量
    down_count = 0
    # 下跌股票的总价
    down_sum = 0
    for item in data:
        # 上涨
        if item["up"]:
            up_count += 1
            up_sum += item["price"]
        else:
            # 下跌
            down_count += 1
            down_sum += item["price"]
    # 上涨股票的比重
    p_up = up_count / count
    # 下跌股票的比重
    p_down = down_count / count
    # 计算涨幅均值
    up_ave = up_sum / up_count
    # 计算下跌均值
    down_ave = down_sum / down_count
    # 计算方差的均值
    up_var = 0
    down_var = 0
    for item in data:
        if item["up"]:
            # 上涨股票差的平方和
            up_var += (item["price"] - up_ave) ** 2
        else:
            #  下跌股票差的平方和
            down_var += (item["price"] - down_ave) ** 2
    up_var /= up_count
    down_var /= down_count
    return {"p_up": p_up, "p_down": p_down, "up_ave": up_ave, "down_ave": down_ave, "up_var": up_var, "down_var": down_var}

# 预测今天收盘时股票的涨跌情况
def bayes(data, PR, open_price):
    # 这里是核心算法
    up_pr = PR["p_up"] * (1 / (2 * 3.14 * PR["up_var"]) ** 0.5) * 2.71828 ** (-((open_price - PR["up_ave"]) ** 2) / (2 * PR["up_var"]))
    down_pr = PR["p_down"] * (1 / (2 * 3.14 * PR["down_var"]) ** 0.5) * 2.71828 ** (-((open_price - PR["down_ave"]) ** 2) / (2 * PR["down_var"]))
    # 返回涨跌对比结果
    return up_pr > down_pr

# 开始预测
def send():
    price = float(price_entry.get())
    PR = probability(stock)
    close_price = bayes(stock, PR, price)
    result_label.config(text=f"今天收盘价格可能{'上涨' if close_price else '下跌！'}")

# 创建主窗口
root = tk.Tk()
root.title("预测股票走势（量化交易）")

# 创建输入框和按钮
tk.Label(root, text="今日股票开盘价：").pack(side="left")
price_entry = tk.Entry(root)
price_entry.pack(side="left")
price_entry.insert(0,10)
tk.Button(root, text="开始预测", command=send).pack(side="left")

# 创建结果标签
result_label = tk.Label(root, text="")
result_label.pack()

# 运行主循环
root.mainloop()